//
//  ApiTestPresent.m
//  EFExtend
//
//  Created by mac on 15/6/29.
//  Copyright (c) 2015年 Eric. All rights reserved.
//

#import "ApiTestPresent.h"
#import "ModelApi.h"

@interface ApiTestPresent ()<APICallBackProtocol>
@property (nonatomic,strong) ModelApi *api;
@end

@implementation ApiTestPresent

DEF_STRING(AppName,@"AppName")
DEF_STRING(Command,@"Command")

- (instancetype)initWithInPlist:(NSString*)inputPlist
{
    self = [super init];
    if (self) {
        self.apiList = [NSDictionary dictionaryWithContentsOfFile:[HMSandbox pathWithbundleName:nil fileName:inputPlist]];
        self.api = [ModelApi api];
    }
    return self;
}
- (NSDictionary*)testApiForApp:(NSString*)app interface:(NSString*)inf{
    NSDictionary *dic = self.apiList;
    dic = [dic objectForKey:app];
    dic = [dic objectForKey:@"commands"];
    return [dic valueForKey:inf];
}

- (id)doSomething:(NSString *)something attributes:(NSArray *)attributeBinded{

    NSString *AppName = [[attributeBinded firstObject] valueForKey:self.AppName];
    NSString *Command = [[attributeBinded firstObject] valueForKey:self.Command];
    
    NSDictionary *dic = [self testApiForApp:AppName interface:Command];
    
    NSDictionary *app = self.apiList;
    NSDictionary *item = [app objectForKey:AppName];
    
    NSDictionary *para = [[dic valueForKey:@"input"] JSONObject];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",[item valueForKey:@"baseUrl"],[item valueForKey:@"path"],Command];
    INFO(@"input",para);
    [self.api postOrGet:[[item valueForKey:@"method"] is:@"POST"] paras:para to:url alias:Command encrypt:[[item valueForKey:@"encrypt"] boolValue] asData:[[item valueForKey:@"asData"] boolValue] form:self];

    return nil;
}

- (void)api:(API *)api doSome:(NSString *)something bean:(WebAPIModelResult*)bean state:(APIProcess)state userinfo:(id)userinfo error:(NSError *)error{
    if ([bean isKindOfClass:[WebAPIModelResult class]]) {
        [self showMessageTip:nil detail:bean.message timeOut:2.f];
    }
}

ON_WebAPI(dlg){
    if (dlg.sending) {
        
        
    }else if (dlg.progressed){
        // 必须在发送web Api 时指定 setWebProcess:YES
        //          dlg.ownRequest.downloadPercent;
        //          dlg.ownRequest.uploadPercent;
        
    }else if (dlg.succeed){
        NSDictionary *dic = [dlg.output objectForKey:[HMWebAPI params]];
        
        [self.delegate presenter:self doSome:dlg.name bean:dic state:PresenterProcessSucced error:nil];
        
    }else if (dlg.failed){
        if (dlg.timeout) {
            [self showFailureTip:@"操作失败" detail:@"链接超时" timeOut:2.f];
            return;
        }
        
        [self showFailureTip:@"网络链接失败" detail:@"数据不存在或网络错误" timeOut:3.f];
    }else if (dlg.cancelled){
        [self showFailureTip:@"操作失败" detail:@"链接已取消" timeOut:2.f];
    }
}

@end
